<template>
  <div class="search-result" v-if="keyWord">
    <!-- 上部分显示是否正在搜索及搜索结果 -->
    <div class="result-header">
      <!-- 判断是否正在搜索中 -->
      <div v-if="isLoading" class="isLoading">
        <p>正在搜索中...</p>
        <p v-loading="isLoading"></p>
      </div>
      <div v-else>
        "{{keyWord}}"
        的搜索结果如下
      </div>
    </div>
    <!-- 下部分为搜索结果（如果搜索不到则不显示） -->
    <div class="result-container" v-show="searchResult.length !== 0">
      <ul v-for="(item, i) in searchResult" :key="i">
        <li class="item"><a href="javascript:;">{{item}}</a></li>
      </ul>
    </div>
  </div>
</template>

<script>
  import pubsub from 'pubsub-js'
  export default {
    name: 'SearchResult',
    data() {
      return {
        isLoading: false,
        searchResult: ['海洋', '海洋', '海洋', '海洋', '海洋', '海洋', '海洋', '海洋', '海洋', '海洋', '海洋', '海洋'],
        keyWord: ''
      }
    },
    methods: {
      // 获取SearchInput里输入的keyWord
      getKeyWord(msgName, data) {
        this.keyWord = data
      }
    },
    mounted() {
      // 订阅getKeyWord事件
      this.pubId = pubsub.subscribe('getKeyWord', this.getKeyWord)
    },
    beforeDestroy() {
      // 取消订阅
      pubsub.unsubscribe(this.pubId)
    }
  } 
</script>

<style scoped>
  .search-result {
    position: absolute;
    left: -35%;
    top: 58px;
    width: 450px;
    text-align: center;
    /* background-color: #fff; */
    background-image: linear-gradient(to bottom, #f2f2f2, #fff);
    border-radius: 10px;
    color: #000;
    font-size: 14px;
    font-weight: 400;
    padding-bottom: 20px;
    box-shadow: 1px 2px 10px #ccc;
    z-index: 9;
  }

  /* 提示框的小三角 */
  .search-result::before {
    content: "";
    position: absolute;
    top: -8px;
    left: 50%;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    border-bottom: 8px solid #f2f2f2;
  }

  .result-header {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 90px;
  }

  .result-header .isLoading {
    display: flex;
    flex-direction: column;
  }

  .isLoading p {
    margin: 10px 0;
  }

  .isLoading p:last-child {
    height: 20px;
  }

  .result-container {
    overflow: auto;
    max-height: 380px;
  }

  .result-container .item {
    text-align: left;
    text-indent: 2em;
    height: 40px;
    line-height: 40px;
  }

  .result-container .item:hover {
    background-color: #eee;
  }
</style>